<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验单号" prop="inspectionCode">
        <el-input v-model="queryParams.inspectionCode" placeholder="请输入检验单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="检验类型" prop="inspectionType">
        <el-select v-model="queryParams.inspectionType" placeholder="请选择检验类型" clearable>
          <el-option label="来料检验(IQC)" value="IQC" />
          <el-option label="过程检验(IPQC)" value="IPQC" />
          <el-option label="成品检验(FQC)" value="FQC" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="已完成" value="0" />
          <el-option label="待确认" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['quality:inspection:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['quality:inspection:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['quality:inspection:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['quality:inspection:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检验记录ID" align="center" prop="inspectionId" />
      <el-table-column label="检验单号" align="center" prop="inspectionCode" />
      <el-table-column label="检验类型" align="center" prop="inspectionType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.inspectionType == 'IQC'" type="primary">来料检验</el-tag>
          <el-tag v-else-if="scope.row.inspectionType == 'IPQC'" type="warning">过程检验</el-tag>
          <el-tag v-else-if="scope.row.inspectionType == 'FQC'" type="success">成品检验</el-tag>
          <span v-else>{{ scope.row.inspectionType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单编号" align="center" prop="orderCode" />
      <el-table-column label="工序名称" align="center" prop="processName" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="标准编码" align="center" prop="standardCode" />
      <el-table-column label="检验员姓名" align="center" prop="inspectorName" />
      <el-table-column label="检验日期" align="center" prop="inspectionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="抽样数量" align="center" prop="sampleQuantity" />
      <el-table-column label="合格数量" align="center" prop="qualifiedQuantity" />
      <el-table-column label="不合格数量" align="center" prop="unqualifiedQuantity" />
      <el-table-column label="检验结论" align="center" prop="conclusion">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.conclusion == '合格'" type="success">合格</el-tag>
          <el-tag v-else-if="scope.row.conclusion == '不合格'" type="danger">不合格</el-tag>
          <span v-else>{{ scope.row.conclusion }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == '0'" type="success">已完成</el-tag>
          <el-tag v-else type="warning">待确认</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['quality:inspection:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['quality:inspection:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改质量检验记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验单号" prop="inspectionCode">
              <el-input v-model="form.inspectionCode" placeholder="请输入检验单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验类型" prop="inspectionType">
              <el-select v-model="form.inspectionType" placeholder="请选择检验类型" @change="handleInspectionTypeChange">
                <el-option label="来料检验(IQC)" value="IQC" />
                <el-option label="过程检验(IPQC)" value="IPQC" />
                <el-option label="成品检验(FQC)" value="FQC" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- IQC专用字段：采购入库单信息 -->
        <div v-if="form.inspectionType === 'IQC'">
          <el-divider content-position="left">采购入库信息</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购入库单" prop="receiptId">
                <el-select v-model="form.receiptId" placeholder="请选择采购入库单" @change="handleReceiptChange" clearable style="width: 100%">
                  <el-option v-for="receipt in receiptList" :key="receipt.receiptId" :label="receipt.receiptCode" :value="receipt.receiptId">
                    <span style="float: left">{{ receipt.receiptCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ receipt.supplierName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName">
                <el-input v-model="form.supplierName" placeholder="自动填充" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- IPQC和FQC共用字段：工单信息 -->
        <div v-if="form.inspectionType === 'IPQC' || form.inspectionType === 'FQC'">
          <el-divider content-position="left">工单信息</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工单" prop="orderId">
                <el-select v-model="form.orderId" placeholder="请选择工单" @change="handleWorkOrderChange" clearable style="width: 100%">
                  <el-option v-for="workOrder in workOrderList" :key="workOrder.orderId" :label="workOrder.orderCode" :value="workOrder.orderId">
                    <span style="float: left">{{ workOrder.orderCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ workOrder.productName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单编码" prop="orderCode">
                <el-input v-model="form.orderCode" placeholder="自动填充" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- IPQC专用字段：工序信息 -->
        <div v-if="form.inspectionType === 'IPQC'">
          <el-divider content-position="left">工序信息</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工序" prop="processId">
                <el-select v-model="form.processId" placeholder="请选择工序" @change="handleProcessChange" clearable style="width: 100%">
                  <el-option v-for="process in processList" :key="process.processId" :label="process.processName" :value="process.processId">
                    <span style="float: left">{{ process.processName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ process.processCode }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工序名称" prop="processName">
                <el-input v-model="form.processName" placeholder="自动填充" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 产品信息 -->
        <el-divider content-position="left">产品信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择产品" @change="handleProductChange" clearable style="width: 100%">
                <el-option v-for="material in materialList" :key="material.materialId" :label="material.materialName" :value="material.materialId">
                  <span style="float: left">{{ material.materialName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ material.materialCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="form.productCode" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.inspectionType === 'FQC'">
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 检验标准 -->
        <el-divider content-position="left">检验标准</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验标准" prop="standardId">
              <el-select v-model="form.standardId" placeholder="请选择检验标准" @change="handleStandardChange" clearable style="width: 100%">
                <el-option v-for="standard in filteredStandardList" :key="standard.standardId" :label="standard.standardName" :value="standard.standardId">
                  <span style="float: left">{{ standard.standardName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ standard.standardCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标准编码" prop="standardCode">
              <el-input v-model="form.standardCode" placeholder="自动填充" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 检验信息 -->
        <el-divider content-position="left">检验信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验员" prop="inspectorName">
              <el-input v-model="form.inspectorName" placeholder="当前登录用户" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验日期" prop="inspectionDate">
              <el-date-picker v-model="form.inspectionDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择检验日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 数量信息 -->
        <el-divider content-position="left">数量信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="抽样数量" prop="sampleQuantity">
              <el-input v-model="form.sampleQuantity" placeholder="请输入抽样数量" @input="calculateUnqualifiedQuantity" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合格数量" prop="qualifiedQuantity">
              <el-input v-model="form.qualifiedQuantity" placeholder="请输入合格数量" @input="calculateUnqualifiedQuantity" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不合格数量" prop="unqualifiedQuantity">
              <el-input v-model="form.unqualifiedQuantity" placeholder="自动计算" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 检验结果 -->
        <el-divider content-position="left">检验结果</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验结论" prop="conclusion">
              <el-select v-model="form.conclusion" placeholder="请选择检验结论">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">已完成</el-radio>
                <el-radio label="1">待确认</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 备注信息 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInspection, getInspection, delInspection, addInspection, updateInspection, checkInspectionCodeUnique } from "@/api/mes/quality/inspection";
import { listWorkOrder } from "@/api/mes/production/workorder";
import { listProcess } from "@/api/mes/production/process";
import { listMaterial } from "@/api/mes/basic/material";
import { listStandard } from "@/api/mes/quality/standard";
import { listReceipt } from "@/api/mes/purchase/receipt";

export default {
  name: "Inspection",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质量检验记录表格数据
      inspectionList: [],
      // 工单列表
      workOrderList: [],
      // 工序列表
      processList: [],
      // 物料列表
      materialList: [],
      // 标准列表
      standardList: [],
      // 采购入库单列表
      receiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectionCode: null,
        orderCode: null,
        productCode: null,
        inspectionType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inspectionCode: [
          { required: true, message: "检验单号不能为空", trigger: "blur" },
          { validator: this.validateInspectionCode, trigger: "blur" }
        ],
        inspectionType: [
          { required: true, message: "检验类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    // 根据检验类型过滤标准列表
    filteredStandardList() {
      if (!this.form.inspectionType) return this.standardList;
      // 这里可以根据检验类型过滤标准，暂时返回全部
      return this.standardList;
    }
  },
  created() {
    this.getList();
    // 获取下拉框数据
    this.getWorkOrderList();
    this.getProcessList();
    this.getMaterialList();
    this.getStandardList();
    this.getReceiptList();
  },
  methods: {
    /** 查询质量检验记录列表 */
    getList() {
      this.loading = true;
      listInspection(this.queryParams).then(response => {
        this.inspectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inspectionId: null,
        inspectionCode: null,
        orderId: null,
        orderCode: null,
        processId: null,
        processName: null,
        productId: null,
        productCode: null,
        productName: null,
        standardId: null,
        standardCode: null,
        inspectorId: null,
        inspectorName: null,
        inspectionDate: null,
        sampleQuantity: null,
        qualifiedQuantity: null,
        unqualifiedQuantity: null,
        conclusion: null,
        status: "0",
        inspectionType: null,
        inspector: null,
        receiptId: null,
        supplierName: null,
        batchNumber: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inspectionId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加质量检验记录";
      // 设置检验员信息为当前登录用户
      this.form.inspectorId = this.$store.getters.userId;
      this.form.inspectorName = this.$store.getters.name;
      this.form.inspectionDate = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inspectionId = row.inspectionId || this.ids
      getInspection(inspectionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改质量检验记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inspectionId != null) {
            updateInspection(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInspection(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inspectionIds = row.inspectionId || this.ids;
      this.$modal.confirm('是否确认删除质量检验记录编号为"' + inspectionIds + '"的数据项？').then(function () {
        return delInspection(inspectionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('quality/inspection/export', {
        ...this.queryParams
      }, `inspection_${new Date().getTime()}.xlsx`)
    },
    /** 获取工单列表 */
    getWorkOrderList() {
      listWorkOrder({}).then(response => {
        this.workOrderList = response.rows || response.data || [];
      });
    },
    /** 获取工序列表 */
    getProcessList() {
      listProcess({}).then(response => {
        this.processList = response.rows || response.data || [];
      });
    },
    /** 获取物料列表 */
    getMaterialList() {
      listMaterial({}).then(response => {
        this.materialList = response.rows || response.data || [];
      });
    },
    /** 获取标准列表 */
    getStandardList() {
      listStandard({}).then(response => {
        this.standardList = response.rows || response.data || [];
      });
    },
    /** 获取采购入库单列表 */
    getReceiptList() {
      listReceipt({ status: 'PENDING' }).then(response => {
        this.receiptList = response.rows || response.data || [];
      });
    },
    /** 检验类型变化处理 */
    handleInspectionTypeChange(inspectionType) {
      // 清空相关字段
      this.form.orderId = null;
      this.form.orderCode = null;
      this.form.processId = null;
      this.form.processName = null;
      this.form.receiptId = null;
      this.form.supplierName = null;
      this.form.batchNumber = null;
      
      // 根据检验类型生成检验单号前缀
      if (inspectionType && !this.form.inspectionId) {
        const date = new Date();
        const dateStr = date.getFullYear().toString() + 
                       (date.getMonth() + 1).toString().padStart(2, '0') + 
                       date.getDate().toString().padStart(2, '0');
        this.form.inspectionCode = inspectionType + dateStr + Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      }
    },
    /** 采购入库单选择变化处理 */
    handleReceiptChange(receiptId) {
      if (receiptId) {
        const selectedReceipt = this.receiptList.find(r => r.receiptId === receiptId);
        if (selectedReceipt) {
          this.form.supplierName = selectedReceipt.supplierName;
          // 可以根据入库单自动填充产品信息
          if (selectedReceipt.productId) {
            this.form.productId = selectedReceipt.productId;
            this.handleProductChange(selectedReceipt.productId);
          }
        }
      } else {
        this.form.supplierName = '';
      }
    },
    /** 工单选择变化处理 */
    handleWorkOrderChange(orderId) {
      if (orderId) {
        const selectedWorkOrder = this.workOrderList.find(w => w.orderId === orderId);
        if (selectedWorkOrder) {
          this.form.orderCode = selectedWorkOrder.orderCode;
          // 可以根据工单自动填充产品信息
          if (selectedWorkOrder.productId) {
            this.form.productId = selectedWorkOrder.productId;
            this.handleProductChange(selectedWorkOrder.productId);
          }
        }
      } else {
        this.form.orderCode = '';
      }
    },
    /** 工序选择变化处理 */
    handleProcessChange(processId) {
      if (processId) {
        const selectedProcess = this.processList.find(p => p.processId === processId);
        if (selectedProcess) {
          this.form.processName = selectedProcess.processName;
        }
      } else {
        this.form.processName = '';
      }
    },
    /** 产品选择变化处理 */
    handleProductChange(productId) {
      if (productId) {
        const selectedProduct = this.materialList.find(m => m.materialId === productId);
        if (selectedProduct) {
          this.form.productCode = selectedProduct.materialCode;
          this.form.productName = selectedProduct.materialName;
        }
      } else {
        this.form.productCode = '';
        this.form.productName = '';
      }
    },
    /** 标准选择变化处理 */
    handleStandardChange(standardId) {
      if (standardId) {
        const selectedStandard = this.standardList.find(s => s.standardId === standardId);
        if (selectedStandard) {
          this.form.standardCode = selectedStandard.standardCode;
        }
      } else {
        this.form.standardCode = '';
      }
    },
    /** 计算不合格数量 */
    calculateUnqualifiedQuantity() {
      const sampleQuantity = parseInt(this.form.sampleQuantity) || 0;
      const qualifiedQuantity = parseInt(this.form.qualifiedQuantity) || 0;
      this.form.unqualifiedQuantity = Math.max(0, sampleQuantity - qualifiedQuantity);
    },
    /** 校验检验单号唯一性 */
    validateInspectionCode(rule, value, callback) {
      if (value) {
        checkInspectionCodeUnique(value).then(response => {
          if (response.data) {
            callback();
          } else {
            callback(new Error("检验单号已存在"));
          }
        });
      } else {
        callback();
      }
    }
  }
};
</script>
